// admin/system/dao/sys_user_role_dao.go
package dao

import (
	"go-admin1/admin/system/model"
	"go-admin1/internal/infrastructure/database"
	"go-admin1/internal/infrastructure/logger"

	"go.uber.org/zap"
	"gorm.io/gorm"
)

// SysUserRoleDao 用户角色关联数据访问接口
type SysUserRoleDao interface {
	Create(userRole *model.SysUserRole) error
	GetByUserID(userID int64) ([]*model.SysUserRole, error)
	GetByRoleID(roleID int64) ([]*model.SysUserRole, error)
	DeleteByUserID(userID int64) error
	DeleteByRoleID(roleID int64) error
	DeleteByUserIDAndRoleID(userID, roleID int64) error
	ListRoleIDsByUserID(userID int64) ([]int64, error)
	ListUserIDsByRoleID(roleID int64) ([]int64, error)
}

type sysUserRoleDao struct {
	db *gorm.DB
}

// NewSysUserRoleDao 创建用户角色关联数据访问实例
func NewSysUserRoleDao() SysUserRoleDao {
	return &sysUserRoleDao{
		db: database.GetDB(),
	}
}

func (ur *sysUserRoleDao) Create(userRole *model.SysUserRole) error {
	logger.Info("创建用户角色关联",
		zap.Int64("user_id", userRole.UserID),
		zap.Int64("role_id", userRole.RoleID))
	return ur.db.Create(userRole).Error
}

func (ur *sysUserRoleDao) GetByUserID(userID int64) ([]*model.SysUserRole, error) {
	logger.Debug("根据用户ID获取用户角色关联", zap.Int64("user_id", userID))
	var userRoles []*model.SysUserRole
	err := ur.db.Where("user_id = ?", userID).Find(&userRoles).Error
	return userRoles, err
}

func (ur *sysUserRoleDao) GetByRoleID(roleID int64) ([]*model.SysUserRole, error) {
	logger.Debug("根据角色ID获取用户角色关联", zap.Int64("role_id", roleID))
	var userRoles []*model.SysUserRole
	err := ur.db.Where("role_id = ?", roleID).Find(&userRoles).Error
	return userRoles, err
}

func (ur *sysUserRoleDao) DeleteByUserID(userID int64) error {
	logger.Info("根据用户ID删除用户角色关联", zap.Int64("user_id", userID))
	return ur.db.Where("user_id = ?", userID).Delete(&model.SysUserRole{}).Error
}

func (ur *sysUserRoleDao) DeleteByRoleID(roleID int64) error {
	logger.Info("根据角色ID删除用户角色关联", zap.Int64("role_id", roleID))
	return ur.db.Where("role_id = ?", roleID).Delete(&model.SysUserRole{}).Error
}

func (ur *sysUserRoleDao) DeleteByUserIDAndRoleID(userID, roleID int64) error {
	logger.Info("根据用户ID和角色ID删除用户角色关联",
		zap.Int64("user_id", userID),
		zap.Int64("role_id", roleID))
	return ur.db.Where("user_id = ? AND role_id = ?", userID, roleID).Delete(&model.SysUserRole{}).Error
}

func (ur *sysUserRoleDao) ListRoleIDsByUserID(userID int64) ([]int64, error) {
	logger.Debug("根据用户ID获取角色ID列表", zap.Int64("user_id", userID))
	var roleIDs []int64
	err := ur.db.Model(&model.SysUserRole{}).Where("user_id = ?", userID).Pluck("role_id", &roleIDs).Error
	return roleIDs, err
}

func (ur *sysUserRoleDao) ListUserIDsByRoleID(roleID int64) ([]int64, error) {
	logger.Debug("根据角色ID获取用户ID列表", zap.Int64("role_id", roleID))
	var userIDs []int64
	err := ur.db.Model(&model.SysUserRole{}).Where("role_id = ?", roleID).Pluck("user_id", &userIDs).Error
	return userIDs, err
}
